package com.atguigu.gmall.order.listener;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.model.enums.OrderStatus;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.enums.PaymentWay;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.mapper.OrderDetailsMapper;
import com.atguigu.gmall.order.mapper.OrderInfoMapper;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.rabbit.constant.RabbitConst;
import com.atguigu.gmall.rabbit.service.RabbitService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;


@Component
public class OrderConsumerListener {
    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private OrderDetailsMapper orderDetailsMapper;

    @RabbitListener(queues = {RabbitConst.QUEUE_DEAD_2})
    public void CancelOrderListener(Long orderId,Message message, Channel channel){
        //取消订单
        orderInfoService.CancelOrder(orderId);
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //更新订单状态
    @RabbitListener(queues = {RabbitConst.QUEUE_PAYMENT_PAY})
    public void updateOrderListener(Long orderId,Message message,Channel channel){
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        List<OrderDetail> orderDetailList = orderDetailsMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_id", orderId));
        if(orderDetailList!=null)
        orderInfo.setOrderDetailList(orderDetailList);

        orderInfo.setOrderStatus(OrderStatus.PAID.name());
        orderInfo.setPaymentWay(orderInfo.getPaymentWay().equals(PaymentWay.ONLINE)?"1":"2");
        orderInfoMapper.updateById(orderInfo);
        Map map = orderInfoService.initWare(orderInfo);
        String orderToJson = JSONObject.toJSONString(map);
        try {
            rabbitService.sendMessage("exchange.direct.ware.stock","ware.stock",orderToJson);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
